<template>
	<div class="news-index">
		<div class="top">
			<h2>行业新闻</h2>
			<div class="search-wapper">
				<input placeholder="请输入关键词" v-model="newsParams.keyword" />
				<div class="btn" @click="search">
					<el-icon size="28">
						<Search />
					</el-icon>
				</div>
			</div>
		</div>
		<div class="tab">
			<div class="tab-item" :class="currentTab == 0 && 'active'" @click="tabClick(0, '')">全部</div>
			<div class="tab-item" :class="currentTab == index + 1 && 'active'" v-for="(item, index) in types"
				@click="tabClick(index + 1, item)">{{ item }}</div>
		</div>

		<div class="news-main">
			<div class="news-list">
				<NewItem v-for="item in newList" :data="item" />
			</div>
			<div class="hots">
				<el-text size="large" style="margin-top: 30px;" type="primary">👍新闻推荐👍</el-text>
				<div class="hot-item" v-for="item in recommendationsList" @click="toDetail(item.id)">{{item.title}}</div>
				<el-text size="large" style="margin-top: 30px;" type="danger">🔥今日热门🔥</el-text>
				<div class="hot-item" v-for="item in hotList" @click="toDetail(item.id)">{{item.title}}</div>
			</div>
		</div>
		<el-badge :is-dot="hasNewNotification" class="notification-badge" style="cursor: pointer">
			<el-button type="primary" circle size="large" class="notification-btn" @click="showNotifications">
				<el-icon>
					<Bell />
				</el-icon>
			</el-button>
		</el-badge>

		<!-- 新增通知弹窗 -->
		<el-dialog v-model="notificationVisible" title="系统通知" width="40%">
			<div v-for="item in notifications" class="notification-item" :class="{ unread: !item.is_read }">
				<div class="notification-header">
					<el-icon :color="getNotificationColor(item.notification_type)">
						<component :is="getNotificationIcon(item.notification_type)" />
					</el-icon>
					<span class="news-title">{{ item.news_title }}</span>
					<el-tag size="small">{{ formatTime(item.created_at) }}</el-tag>
				</div>
				<div class="notification-content">{{ item.content }}</div>
			</div>
			<el-pagination small layout="prev, pager, next" :total="pageData.total" v-model:current-page="pageData.page"
				v-model:page-size="pageData.page_size" @current-change="handlePageChange"
				style="margin-top: 20px; justify-content: center" />
		</el-dialog>
	</div>
</template>
<script setup lang="ts">
import { recommendations, categories, news_list, hot_ranking, notifications_list, notifications_read } from '/@/api/news.ts'
import { ref } from 'vue'
import { Bell, Star, ChatDotRound, Thumb } from '@element-plus/icons-vue'
import NewItem from "./component/NewItem.vue";
import { useRouter } from "vue-router";
import { useStorage } from '@vueuse/core'
import dayjs from "dayjs";

const formatTime = (time) => {
	return dayjs(time).format('YYYY-MM-DD HH:mm')
}
// 新增状态
const notificationVisible = ref(false)
const lastNotificationId = ref(
	Number(localStorage.getItem('last_notification_id')) || 0
)
const hasNewNotification = ref(false)
const pageData = ref({
	page: 1,
	page_size: 10,
	total: 0
})
// 新增通知数据
const notifications = ref([])

const markAsRead = async (notification) => {
	// if (notification.is_read) return
	// const jsonData = {
	// 	id: notification.id,
	// 	is_read: true,
	// }
	// console.log(jsonData)
	// await notifications_read(jsonData)
	// notification.is_read = true
}
// 修改获取通知方法
const getNotifications = async () => {
	const res = await notifications_list({ page: pageData.value.page, page_size: pageData.value.page_size })
	notifications.value = res.data.notifications
  	pageData.value.total = res.data.total
	// 检查新通知
	if (notifications.value.length > 0) {
		const latestId = notifications.value[0].id
		hasNewNotification.value = latestId > lastNotificationId.value && !notificationVisible.value
	}
}

const handlePageChange = (newPage) => {
  pageData.value.page = newPage
  getNotifications()
}

// 新增通知类型映射
const getNotificationIcon = (type) => {
	const icons = {
		'like': Star,
		'comment': ChatDotRound,
		'reply': ChatDotRound
	}
	return icons[type] || Bell
}

const getNotificationColor = (type) => {
	const colors = {
		'like': '#FF6B6B',
		'comment': '#4D96FF',
		'reply': '#6BCB77'
	}
	return colors[type] || '#909399'
}

// 修改标记已读逻辑
const showNotifications = () => {
	notificationVisible.value = true
	// 更新最后已知ID
	if (notifications.value.length > 0) {
		localStorage.setItem('last_notification_id', notifications.value[0].id)
		lastNotificationId.value = notifications.value[0].id
		hasNewNotification.value = false
	}
}
//分类
const types = ref([])
const getTypes = async () => {
	const res = await categories()
	types.value = res.data.categories
}
//推荐列表
const recommendationsList = ref([])
const getRecommendas = async () => {
	const res = await recommendations()
	recommendationsList.value = res.data
}

//新闻列表
const newList = ref([])
const total = ref(0)
const newsParams = ref({
	keyword: '',
	page: 1,
	pageSize: 10,
	category: ''
})
const getNews = async () => {
	const res = await news_list(newsParams.value)
	newList.value = [...newList.value, ...res.data.news]
	total.value = res.data.total
}


const currentTab = ref(0)
const tabClick = (index: number, value: string, cleanKeyword: boolean = true) => {
	currentTab.value = index
	newsParams.value.page = 1
	newsParams.value.category = value;
	if (cleanKeyword) {
		newsParams.value.keyword = ''
	}
	newList.value = []
	getNews()
}
const search = () => {
	tabClick(0, '', false)
}
const hotList = ref([])
const getHotList = async () => {
	const res = await hot_ranking()
	hotList.value = res.data
}


const init = () => {
	getTypes()
	getRecommendas()
	getNews()
	getHotList()
	getNotifications()
}
init()

const router = useRouter()
const toDetail = (id: number) => {
	const url = router.resolve({
		path: `/news-detail/${id}`
	}).href;
	window.open(url, '_blank');
}
</script>
<style scoped lang="scss">
.flex-center {
	display: flex;
	align-items: center;
	justify-content: center;
}

.news-index {
	//-60是减去顶部导航栏高度
	min-height: calc(100vh - 60px);
	width: 100%;
	background: #fefefe;
	position: static;
	/* 关键修改 */
	overflow: visible;

	/* 关键修改 */
	.top {
		width: 100%;
		height: 400px;
		background: url("./imgs/header_bg.jpeg") no-repeat;
		background-size: 100% auto;
		aspect-ratio: 5/1;
		padding-top: 50px;
		display: flex;
		flex-direction: column;
		align-items: center;

		h2 {
			color: #fff;
			font-size: 36px;
			font-weight: 600;
			text-align: center;
		}

		.search-wapper {
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 600px;
			height: 50px;
			background: #fff;
			border-radius: 14px;
			overflow: hidden;
			margin-top: 50px;

			input {
				flex: 1;
				padding: 0 10px;
				height: 45px;
				border: none;
				font-size: 24px;
				color: #303133;

				&:focus {
					outline: none;
				}

				::placeholder {
					color: #34495e;
				}
			}

			.btn {
				width: 50px;
				height: 100%;
				background: #409eff;
				color: #fff;
				@extend .flex-center;
				cursor: pointer;

				&:active {
					background: #007aef;
				}
			}
		}
	}

	.tab {
		height: 50px;
		position: sticky;
		top: -1px;
		/* 修复边缘粘连问题 */
		margin-top: -1px;
		background: #fff;
		box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
		@extend .flex-center;

		.tab-item {
			@extend .flex-center;
			min-width: 100px;
			height: 40px;
			padding: 0 20px;
			border: 1px solid #1365b6;
			border-radius: 20px;
			margin: 0 14px;
		}

		.active {
			background: #1365b6;
			color: #fff;
		}
	}

	.news-main {
		flex: 1;
		min-height: calc(100vh - 60px - 50px - 400px);
		background: rgb(243.9, 244.2, 244.8);
		display: flex;

		.news-list {
			width: calc(100% - 800px);
			margin-left: 400px;
			background: #fff;
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 20px;
			padding: 20px;
		}

		.hots {
			width: 400px;
			display: flex;
			flex-direction: column;
			padding: 0 30px;

			.subtitle {
				font-size: 18px;
				line-height: 30px;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.hot-item {
				width: 100%;
				padding: 8px 20px;
				height: 30px;
				display: flex;
				align-items: center;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				border-radius: 8px;
				cursor: pointer;

				&:hover {
					background: rgb(159.5, 206.5, 255);
				}
			}
		}

	}

}

.notification-badge {
	position: fixed;
	right: 40px;
	bottom: 40px;
	z-index: 2000;
}

.notification-item {
	padding: 12px;
	border-bottom: 1px solid #eee;

	&.unread {
		background-color: #f5f7fa;
	}

	.notification-header {
		display: flex;
		align-items: center;
		gap: 8px;
		margin-bottom: 8px;

		.news-title {
			flex: 1;
			font-weight: 500;
		}
	}

	.notification-content {
		color: #606266;
		padding-left: 28px;
	}
}
</style>
